/*
  此 hooks 用于处理用户行为(点赞、取消点赞、踩、取消踩、收藏、取消收藏)
  作用范围： 
  forum 页面中的 article-item 组件
  articleDetail 页面
*/

import { useForumStore } from "@/store/forum.js";
import { useUserStore } from "@/store/user.js";
import { apiAction } from "@/api/forum";
import { storeToRefs } from "pinia";
const forumStore = useForumStore();
const { articleList } = storeToRefs(forumStore);
const userStore = useUserStore();
const { userInfo,token } = storeToRefs(userStore);


export default function () {
  // 登录校验
  const ensureLogin = () => {
    if (!token.value) {
      uni.showModal({
        title: "温馨提示",
        content: "请登录后做此操作",
        showCancel: false,
        success: () => {
          uni.switchTab({ url: "/pages/my/my" });
        },
      });
      return false;
    }
    
    return true;
  };
  // 用户行为
  const handleAction = async (params) => {
    //待做 --- 登录判断
    if (!ensureLogin()) return;
    params.userId = userInfo.value.id;
    //在 pinia 仓库中查找用户所点击的文章信息
    const result = articleList.value.find((i) => i.id === params.postId);
    if (!result) return;
    /*点赞*/
    if (params.actionType === 1) {
      const liked = result.actionType1 !== 0;
      // 已经点赞过了 - 取消点赞
      if (liked) {
        params.actionType = 4;
        result.actionType1 = 0;
        result.upvote--;
        await apiAction(params);
        return;
      }

      //更新pinia
      // 点赞
      params.actionType = 1;
      result.actionType1 = 1;
      result.upvote++;
      await apiAction(params);
      //如果有踩过，取消踩
      if (result.actionType3 !== 0) {
        params.actionType = 6;
        result.actionType3 = 0;
        await apiAction(params);
      }
    }
    /*收藏*/
    if (params.actionType === 2) {
      const collected = result.actionType2 !== 0;
      //如果收藏过就取消收藏
      if (collected) {
        params.actionType = 5;
        result.actionType2 = 0;
        await apiAction(params);
        return;
      }
      //收藏 更新 pinia
      result.actionType2 = 1;
      result.enshrine++;
      await apiAction(params);
    }
    /*踩*/
    if (params.actionType === 3) {
      // console.log('ok');
      const disliked = result.actionType3 !== 0;
      //踩过了，就取消踩
      if (disliked) {
        params.actionType = 6;
        result.actionType3 = 0;
        await apiAction(params);
        return;
      }
      //更新pinia
      params.actionType = 3;
      result.actionType3 = 1;
      await apiAction(params);
      // 如果点赞了，取消点赞
      if (result.actionType1 !== 0) {
        params.actionType = 4;
        result.actionType1 = 0;
        result.upvote--;
        await apiAction(params);
      }
    }
  };
  return {
    handleAction,
    ensureLogin,
  };
}